package rhinestone.Model;

import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Calendar;
import java.io.Serializable;

/**
 * This class represents an order.
 *
 * @author middreks
 * @version 2010.12.16.
 */
public class Order implements Serializable {
    private static int ordersID = 0;
	private int id;
    private GregorianCalendar registrationDate;
    private String status;
    private HashMap<Product, Integer> products; // HashMap<Product, amount>

    /**
     * Constructor for an Order
     * 
     * @param id The unique ID of the order
     * @param registrationDate The date when the order was added
     * @param arrivalDate The date when the ordered products will arrive
     * @param status The status of the order (pending, in progress, etc.)
     * @param products This HashMap holds the ordered products along
     * with the amount what is needed
     */
    public Order() {
        id = ++ordersID;
        registrationDate = new GregorianCalendar();
        status = "Pending";
        products = new HashMap<Product, Integer>();
    }

    //
    // Getters and setters for this class
    //

    public int getId() {
        return id;
    }

	public void addProduct(Product product, int amount) {
		if(!products.containsKey(product))
			products.put(product, amount);
		else {
			int amountInOrder = products.remove(product);
			products.put(product, (amount + amountInOrder));
		}
	}

	public void removeProduct(Product product, int amount) {
		int amountInOrder = products.remove(product);
		if(amountInOrder <= amount || amount == 0) {
			products.remove(product);
			System.out.println(" --- Product removed ---");
		}
		else {
			products.put(product, (amountInOrder - amount));
			System.out.println(amount + " products removed.");
		}
	}

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

	public int getProductCount() {
		return products.size();
	}

	@Override
	public String toString() {
		String output = "----------------------------------";
		output += "\n\tORDERED GOODS:";
		Iterator<Product> it = products.keySet().iterator();
		while(it.hasNext()) {
			Product product = it.next();
			output += "\n" + products.get(product) + "x " + product.getName() + "("+product.getBarcode()+")";
		}
		output += "\n----------------------------------";
		output += "\nREGISTRATION DATE: " + registrationDate.get(Calendar.YEAR) + " " + (registrationDate.get(Calendar.MONTH) + 1) + " " + registrationDate.get(Calendar.DAY_OF_MONTH);
		output += "\nSTATUS: " + status;
		output += "\n----------------------------------";
		return output;
	}
}